package cn.wolfcode.shop.cloud.service.impl;

import cn.wolfcode.shop.cloud.common.BusinessException;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.mapper.UserMapper;
import cn.wolfcode.shop.cloud.msg.MemberCodeMsg;
import cn.wolfcode.shop.cloud.redis.RedisService;
import cn.wolfcode.shop.cloud.service.IUserService;
import cn.wolfcode.shop.cloud.util.Md5Util;
import cn.wolfcode.shop.cloud.util.MemberKeyPrefixUtil;
import cn.wolfcode.shop.cloud.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;
    @Override
    public User get(Long id) {
        return userMapper.selectByUserId(id);
    }

    @Override
    public String doLogin(LoginVO loginVO) {
        if (StringUtils.isEmpty(loginVO.getUsername())||StringUtils.isEmpty(loginVO.getPassword())){
            throw new BusinessException(MemberCodeMsg.USERNAME_AND_PASSWORD_NOT_NULL);
        }
        long id = Long.parseLong(loginVO.getUsername());

        User user = get(id);
        if (user==null){
            throw new BusinessException(MemberCodeMsg.USER_NOT_EXISTS);
        }
        String enByPass = Md5Util.endCode(user.getSalt(), loginVO.getPassword());
        if (!enByPass.equals(user.getPassword())){
            throw new BusinessException(MemberCodeMsg.PASSWORD_ERROR);
        }
        String token = createToken(user);
        return token;
    }

    private String createToken(User user) {
        //设置token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //放到redis
        redisService.set(MemberKeyPrefixUtil.USER_TOKEN, token, user);
        return token;
    }

    @Override
    public Boolean refreshRedisToken(String token) {
        Boolean exists = redisService.exists(MemberKeyPrefixUtil.USER_TOKEN, token);
        if (exists){
            redisService.expire(MemberKeyPrefixUtil.USER_TOKEN,token);
            return true;
        }
        return false;
    }

    @Override
    public User getCurrent(String token) {
       if (StringUtils.isEmpty(token)){
           return null;
       }
        return redisService.get(MemberKeyPrefixUtil.USER_TOKEN,token ,User.class );
    }
}
